package com.xxl.job.executor.core.utils;

import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FtpUtil {

    private static FTPClient ftpClient;

    public FtpUtil() {
    }

    /**
     * 上传文件到FTP服务器
     *
     * @param path
     * @param file
     * @return
     */
    public static boolean uploadFile(String path, File file) {
        try {
            if (connect()) {
                FileInputStream fileInputStream;
                try {
                    // 切换工作目录
                    if (ftpClient.changeWorkingDirectory(path)) {
                        System.out.println("已切换到目录--" + ftpClient.printWorkingDirectory());
                        ftpClient.setBufferSize(2048);
                        ftpClient.setControlEncoding("GBK");
                        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);      //设置文件格式为二进制格式
                        ftpClient.enterLocalPassiveMode();
                        fileInputStream = new FileInputStream(file);
                        String upFileName = file.getName().concat(".TEMP");
                        boolean upload = ftpClient.storeFile(upFileName, fileInputStream);
                        ftpClient.disconnect();
                        fileInputStream.close();
                        if (upload) {
                            // 上传成功更改文件名
                            System.out.println("上传文件---" + upFileName + "成功");
                            File f = new File(ConfigUtil.FTPFILE + path + "/" + upFileName);

                            f.renameTo(new File(ConfigUtil.FTPFILE + path + "/" + file.getName()));
                            if (f.exists()) {
                                f.delete();
                            }
                            System.out.println("更改文件---" + upFileName + "---为---" + file.getName() + "成功");
                            System.out.println("----文件 " + file.getName() + " 上传成功----");
                            return true;
                        } else {
                            System.out.println("----文件 " + file.getName() + " 上传失败----");
                            return false;
                        }

                    }
                } catch (Exception e) {
                    System.out.println("工作目录----" + path + "不存在");
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 连接到FTP服务器
     *
     * @return
     */
    private static boolean connect() {
        boolean connectResult = false;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ConfigUtil.HOST, ConfigUtil.PORT);
            connectResult = ftpClient.login(ConfigUtil.USERNAME, ConfigUtil.PASSWORD);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connectResult;
    }


}
